from django.db import migrations


def fix_zero_datetimes(apps, schema_editor):
    connection = schema_editor.connection
    fixes = [
        ('spider_crawl_task', ['created_at', 'updated_at', 'crawled_at']),
        ('spider_raw_html', ['created_at']),
        ('spider_list_item', ['publish_time', 'created_at', 'updated_at']),
        ('spider_detail_item', ['created_at', 'updated_at']),
        ('spider_sub_detail_item', ['created_at']),
    ]
    with connection.cursor() as cursor:
        for table, columns in fixes:
            for col in columns:
                try:
                    cursor.execute(f"UPDATE `{table}` SET `{col}`=NULL WHERE `{col}`='0000-00-00 00:00:00'")
                except Exception:
                    pass


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ('spider', '0012_subdetailitem_recognized_confidence_reason'),
    ]

    operations = [
        migrations.RunPython(fix_zero_datetimes, noop_reverse),
    ]